#!/usr/bin/python
# -*- coding: utf-8 -*-
#-------------------------------------------------
#Create At: 2009-4-21 下午01:31:10 
#Create By: Fla.sam
#
#DESC: pure-ftpd admin core models
#
#-------------------------------------------------


from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save, pre_delete, post_save
from adodbapi.adodbapi import type
import os
import os.path
import subprocess
import sys
import unipath

# Create your models here.

GENDER_CHOICES = ( ( 'M', u'男' ),
                  ( 'F', u'女' ) )

class Department( models.Model ):
    name = models.CharField( verbose_name = u'院/系 名称', \
                            max_length = 100, \
                            help_text = u'院/系的中文名称' ) 
    e_name = models.CharField( verbose_name = u'院/系 英文名称', \
                              max_length = 30, \
                              help_text = u'院/系的英文名称,该字段将被作为用户组的分类. 请不要包含空格' )
    
    def __unicode__( self ):
        return u'%s(%s)' % ( self.name, self.e_name )
    
    class Meta:
        ordering = ['name']
        verbose_name = u'院/系'
        verbose_name_plural = u'%s管理' % verbose_name

class PureUser( models.Model ):
    
    loginname = models.CharField( verbose_name = u'用户名', \
                                  max_length = 23, \
                                  help_text = u'''学生请填写学号作为登陆用户名. 教师请勿在此申请,请直接联系管理员''', \
                                  unique = True, \
                                  )
    password = models.CharField( verbose_name = u'密码', \
                                 max_length = 48 )

    homedir = models.CharField( verbose_name = u'用户登陆根目录', \
                                max_length = 255,
                                help_text = u'默认FTP根路径:%s' % settings.PURE_FTPD_ROOT_PATH, \
                                default = settings.PURE_FTPD_ROOT_PATH )

    quotafiles = models.PositiveIntegerField( verbose_name = u'文件数限额', \
                                              help_text = u'用户最多允许上传的文件数限制', \
                                              default = 500 )
    quotasize = models.PositiveIntegerField( verbose_name = u'磁盘限额', \
                                             help_text = u'用户上传的磁盘限额, 单位:MB', \
                                             default = 150 )
    bandwidthup = models.PositiveIntegerField( verbose_name = u'上传带宽', \
                                               help_text = u'用户上传带宽限制,单位: KB/s', \
                                               default = 1024 )
    bandwidthdn = models.PositiveIntegerField( verbose_name = u'下载带宽', \
                                               help_text = u'用户下载带宽限制,单位: KB/s', \
                                               default = 1024 )
    
    useable = models.BooleanField( verbose_name = u'账户是否可用', \
                                   default = False, \
                                   help_text = u'''如果是'False',则该账户未启用或已经被禁止''' )
    
    techer = models.BooleanField( verbose_name = u'是否教师', \
                                 default = False, \
                                 help_text = u'如果是True, 则该账户的跟路径为ftp根路径' )
    
    uid = models.PositiveIntegerField( verbose_name = u'Linux 系统用户id(uid)', default = settings.PURE_DEFAULT_UID )
    gid = models.PositiveIntegerField( verbose_name = u'Linux 系统组id(gid)' , default = settings.PURE_DEFAULT_GID )
    
    createdatetime = models.DateTimeField( verbose_name = u'申请时间', \
                                           auto_now_add = True ) 
    name = models.CharField( verbose_name = u'姓名', \
                             max_length = 10 )
    gender = models.CharField( verbose_name = u'性别', \
                               max_length = 2, \
                               choices = GENDER_CHOICES )
    department = models.ForeignKey( Department, \
                                    verbose_name = u'所属院/系' )
    
    def __unicode__( self ):
        return u'%s(%s-%s)' % ( self.loginname, self.name, self.department )
    
    class Meta:
        ordering = ['loginname']
        verbose_name = u'用户'
        verbose_name_plural = u'%s管理' % verbose_name
        
def set_homedir( sender, instance, signal, *args, **kwargs ):

    u_obj = instance
    
    #set user homedir
    if u_obj.techer:
        _p = os.path.join( settings.PURE_FTPD_ROOT_PATH, 'techers', \
                                     '%s-%s' % ( u_obj.loginname, u_obj.name ) )
        u_obj.homedir = _p + '/./'
        u_obj.uid = settings.PURE_TECHER_UID
        u_obj.quotafiles = 10000
        u_obj.quotasize = 2048
        u_obj.bandwidthup = 1024
        u_obj.bandwidthdn = 1024
    else:
        _p = os.path.join( settings.PURE_FTPD_ROOT_PATH, 'students', \
                           '%s-%s' % ( u_obj.department.e_name, u_obj.department.name ), \
                           '%s-%s' % ( u_obj.loginname, u_obj.name ) )
        u_obj.homedir = _p + '/./'
        u_obj.uid = settings.PURE_STUDENT_UID
pre_save.connect( set_homedir, sender = PureUser )

def mk_homedir( sender, instance, signal, *args, **kwargs ):
    
    u_obj = instance
    
    print _homedir, type( _homedir )
    _homedir = u_obj.homedir
    
    print _homedir, type( _homedir )
    
    _public_dir = unipath.Path( _homedir, settings.FTPD_PUBLIC_DIR )
    _techer_dir = unipath.Path( _homedir, settings.FTPD_TECHER_DIR )
    _student_dir = unipath.Path( _homedir, settings.FTPD_STUDENT_DIR )
    
        
    # if user enabled  create a link in user home dir
    # for debug test system 
    if sys.platform == 'linux2': 
        _homedir.mkdir( parents = True )
        subprocess.Popen( 'chmod 1755 -R %s' % str( _homedir ) , shell = True )
        
        if u_obj.techer:
            #添加 目录属权限
            subprocess.Popen( 'chown %s:%s -R %s' % ( settings.PURE_TECHER_UID, settings.PURE_DEFAULT_GID, str( _homedir ) ), shell = True )
            subprocess.Popen( 'setfacl -m user:%s:rwx -R %s' % ( settings.PURE_ADMIN_UID, str( _homedir ) ), shell = True )
           
        else:
            subprocess.Popen( 'chown %s:%s -R %s' % ( settings.PURE_STUDENT_UID, settings.PURE_DEFAULT_GID, str( _homedir ) ), shell = True )
            subprocess.Popen( 'setfacl -m user:%s:rwx -R %s' % ( settings.PURE_ADMIN_UID, str( _homedir ) ), shell = True )
         
        #remove all link
        try:
            _public_dir.remove()
            _techer_dir.remove()
            _student_dir.remove()
        except:
            pass
        
        if u_obj.useable:
            #default add public link to all user
            _public_dir.make_relative_link_to( os.path.join( settings.PURE_FTPD_ROOT_PATH, 'public' ) )
                        
            if u_obj.techer:
                pass
            else:
                _techer_dir.make_relative_link_to( os.path.join( settings.PURE_FTPD_ROOT_PATH, 'techers' ) )
    else:
        print 'make homedir', _homedir
        print 'make public link', _public_dir
        print 'make techer link', _techer_dir
        print 'make student link', _student_dir
post_save.connect( mk_homedir, sender = PureUser )

def clean_homedir( sender, instance, signal, *args, **kwargs ):
    u_obj = instance
    _h = unipath.Path( u_obj.homedir.encode( settings.FILE_SYSTEM_CODE ) )
    _homedir = _h.absolute()
    if sys.platform == 'linux2':
        try:
            _homedir.rmtree( parents = False )
        except:
            pass
    else:
        print 'remove homedir', _homedir
pre_delete.connect( clean_homedir, sender = PureUser )
